package com.qian2.pricesharingapplication.shoppinglist;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pricesharingapplication.R;
import com.qian2.pricesharingapplication.MainActivity;

import de.timroes.swipetodismiss.SwipeDismissList;
import de.timroes.swipetodismiss.SwipeDismissList.UndoMode;

public class ShoppingList extends ListActivity{
	ArrayAdapter<String> mAdapter;
	Intent intent;
	TextView ItemId;
	SqliteController controller = new SqliteController(this);
	// Set up ListView example


	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shoppinglist);
		((MainActivity) getParent()).temp(this);
		refresh();
	}


	public void refresh() {
		ArrayList<HashMap<String,Object>> studentList =  controller.getAllItems();
		ListView lv = getListView();
		if(studentList.size()!=0) {
			lv.setOnItemLongClickListener(new OnItemLongClickListener(){

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, final View view,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					PopupMenu popup = new PopupMenu(getBaseContext(), view);
					getMenuInflater().inflate(R.menu.shopping_list, popup.getMenu());
					popup.show();	
					popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
						@Override
						public boolean onMenuItemClick(MenuItem item) {
							// TODO Auto-generated method stub
							if (item.getItemId()==R.id.edit){

								AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingList.this);
								builder.setTitle(getString(R.string.edit));

								// Set up the input
								final EditText input = new EditText(ShoppingList.this);
								// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
								input.setInputType(InputType.TYPE_CLASS_TEXT);
								builder.setView(input);

								// Set up the buttons
								builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
									@Override
									public void onClick(DialogInterface dialog, int which) {
										String new_list = "";
										new_list = input.getText().toString();
										HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
										queryValues.put("ItemName", new_list);
										TextView ItemId = (TextView) view.findViewById(R.id.ItemId);
										queryValues.put("ItemId", ItemId.getText().toString());
										controller.updateShoppingList(queryValues);
										refresh();
									}
								});
								builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.cancel();
									}
								});

								builder.show();


							}
							else if (item.getItemId()==R.id.remove){
								deleteStudent(view);
							}
							return false;
						}
					});
					return false;
				}



			});
			lv.setOnItemClickListener(new OnItemClickListener() {
				@Override 
				public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
					AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingList.this);
					builder.setTitle(getString(R.string.search));

					// Set up the buttons
					builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
					builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
						@Override
						public void onClick(DialogInterface dialog, int which) {
							((MainActivity) getParent()).return_tab().setCurrentTabByTag("Search");
						((EditText)	((MainActivity) getParent()).getSearch_activity().findViewById(R.id.editText2)).setText(((TextView)view.findViewById(R.id.ItemName)).getText().toString());
						}
					});


					builder.show();
				}
			});
		}
		ListAdapter adapter = new SimpleAdapter( ShoppingList.this,studentList, R.layout.view_item_entry, new String[] {"ItemId","ItemName"}, new int[] {R.id.ItemId, R.id.ItemName})
		{

			/* (non-Javadoc)
			 * @see android.widget.SimpleAdapter#getView(int, android.view.View, android.view.ViewGroup)
			 */
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				View view = super.getView(position, convertView, parent);  
				@SuppressWarnings("unchecked")  
				final HashMap<String,Object> map = (HashMap<String, Object>) this.getItem(position);  

				CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox1);  
				//if (Boolean.parseBoolean(s)map.get("Bought"))
				if (map.get("Bought").toString().equals("1")){
					checkBox.setChecked((Boolean) true);
					TextView ItemName2 = (TextView) ((View) view.findViewById(R.id.ItemName));
					ItemName2.setPaintFlags(ItemName2.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
					ItemName2.setTextColor(getResources().getColor(R.color.grey));
				}
				else {
					checkBox.setChecked((Boolean) false);
					TextView ItemName2 = (TextView) ((View) view.findViewById(R.id.ItemName));
					ItemName2.setPaintFlags(ItemName2.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
					ItemName2.setTextColor(Color.parseColor("#4C9900"));
				}


				checkBox.setOnClickListener(new View.OnClickListener() {  
					@Override  
					public void onClick(View view) {  
						//						                        map.put("Bought", ((CheckBox)view).isChecked());
						HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
						TextView ItemName = (TextView) ((View) view.getParent()).findViewById(R.id.ItemName);
						queryValues.put("ItemName", ItemName.getText().toString());
						TextView ItemId = (TextView) ((View) view.getParent()).findViewById(R.id.ItemId);
						queryValues.put("ItemId", ItemId.getText().toString());
						if (((CheckBox)view).isChecked()){
							queryValues.put("Bought", 1);
							ItemName.setPaintFlags(ItemName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
							ItemName.setTextColor(getResources().getColor(R.color.grey));
						}
						else
						{
							queryValues.put("Bought", 0);
							ItemName.setPaintFlags(ItemName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
							ItemName.setTextColor(Color.parseColor("#A4C739"));
						}
						controller.updateShoppingList(queryValues);
					}  
				});  
				return view;
			}}; 
			lv.setAdapter(adapter);



			SwipeDismissList.OnDismissCallback callback = new SwipeDismissList.OnDismissCallback() {
				// Gets called whenever the user deletes an item.
				public SwipeDismissList.Undoable onDismiss(AbsListView listView, final int position) {
					// Get your item from the adapter (mAdapter being an adapter for MyItem objects)
					//final String deletedItem = mAdapter.getItem(position);
					final TextView ItemId = (TextView) listView.getChildAt(position).findViewById(R.id.ItemId);
					System.out.println(ItemId.getText().toString());
					final TextView ItemName = (TextView) listView.getChildAt(position).findViewById(R.id.ItemName);
					deleteStudent(listView.getChildAt(position));
					// Delete item from adapter
					//mAdapter.remove(deletedItem);
					// Return an Undoable implementing every method
					return new SwipeDismissList.Undoable() {

						// Method is called when user undoes this deletion
						public void undo() {
							// Reinsert item to list
							HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
							queryValues.put("ItemName", ItemName.getText().toString());
							queryValues.put("ItemId", ItemId.getText().toString());
							System.out.println(ItemId.getText().toString());
							controller.insertItem_undo(queryValues);
							refresh();
						}

						// Return an undo message for that item
						public String getTitle() {
							return ItemName.getText().toString() + " deleted";
						}

						// Called when user cannot undo the action anymore
						public void discard() {
							// Use this place to e.g. delete the item from database
							//TODO finallyDeleteFromSomeStorage(deletedItem);
						}
					};
				}
			};



			UndoMode mode = SwipeDismissList.UndoMode.SINGLE_UNDO;
			SwipeDismissList swipeList = new SwipeDismissList(lv, callback, mode);
			swipeList.setAutoHideDelay(4000);
	}

	public void add_item() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("New Item");

		// Set up the input
		final EditText input = new EditText(this);
		// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
		input.setInputType(InputType.TYPE_CLASS_TEXT);
		builder.setView(input);

		// Set up the buttons
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String new_list = "";
				new_list = input.getText().toString();
				HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
				queryValues.put("ItemName", new_list);
				controller.insertItem(queryValues);
				refresh();
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		builder.show();
	}
	
	public static void add_item(String item_name,Context context) {

				String new_list = "";
				HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
				queryValues.put("ItemName", item_name);
				SqliteController controller2=new SqliteController(context);
				controller2.insertItem(queryValues);

	}
	//This is a test
	private void deleteStudent(View view) {
		TextView ItemId = (TextView) view.findViewById(R.id.ItemId);
		HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
		queryValues.put("ItemId", ItemId.getText().toString());
		controller.removeItem(queryValues);
		refresh();
	}

}
